//
//  WATFCommon.swift
//  WiFiFaster
//
//  Created by one on 2023/12/28.
//

import UIKit
import SnapKit


let watf_SCREEN_WIDTH  =  UIScreen.main.bounds.size.width
let watf_SCREEN_HEIGHT =  UIScreen.main.bounds.size.height
class WATFCommon: NSObject {
    @objc static func watf_getHXColorValue(rgb: UInt,a:CGFloat = 1) -> UIColor {
        return UIColor(
            red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgb & 0x0000FF) / 255.0,
            alpha: a
        )
    }
    
    @objc static var watf_statusBarHeight: CGFloat {
        return watf_isVirtualTop ? 44 : 20
    }
    @objc static var watf_isVirtualTop: Bool {
        if #available(iOS 11.0, *) {
            let keyWindow: UIWindow? = WATFAppDelegate.watf_shared().watf_window ?? nil
            if keyWindow != nil {
                let topSafeInset: CGFloat = keyWindow!.safeAreaInsets.top
                if topSafeInset > 20.0 {
                    return true
                }
            }
        }
        return false
    }
    
    @objc static var watf_XBottomSpace: CGFloat {
        return watf_isVirtualHome ? 34 : 0
    }
    
    @objc static var watf_tabbarH: CGFloat {
        return watf_XBottomSpace+49
    }
    @objc static var watf_isPhone6: Bool {
        return watf_SCREEN_HEIGHT == 667
    }
    @objc static var watf_isVirtualHome: Bool {
        if #available(iOS 11.0, *) {
            let keyWindow: UIWindow? = WATFAppDelegate.watf_shared().watf_window ?? nil
            if keyWindow != nil {
                let bottomSafeInset: CGFloat = keyWindow!.safeAreaInsets.bottom
                if bottomSafeInset > 0.0 {
                    return true
                }
            }
        }
        return false
    }
    @objc static var watf_version: String {
        return Bundle.main.infoDictionary!["CFBundleShortVersionString"] as? String ?? ""
    }
    @objc static var watf_bundleIdentifier: String {
        return Bundle.main.bundleIdentifier ?? ""
        
    }
    @objc static var watf_buildVersion: String {
        return Bundle.main.infoDictionary!["CFBundleVersion"] as? String ?? ""
        
    }
    @objc static var watf_idfv: String {
        return UIDevice.current.identifierForVendor?.uuidString ?? ""
    }
    @objc static func watf_getTopViewController(vc: UIViewController?) -> UIViewController? {
        if let nav = vc as? UINavigationController {
            return watf_getTopViewController(vc: nav.visibleViewController)
        }
        else if let tab = vc as? UITabBarController, let selected = tab.selectedViewController {
            return watf_getTopViewController(vc: selected)
        }
        else if let persented = vc?.presentedViewController {
            return watf_getTopViewController(vc: persented)
        }
        return vc
    }
    static func watf_alertShow(watf_title: String, watf_message: String, watf_vc: UIViewController? = nil, watf_comlete:(()->())? = nil) {
        var watf_vc = watf_vc
        if watf_vc == nil {
            watf_vc = WATFAppDelegate.watf_shared().watf_window?.rootViewController
        }
        DispatchQueue.main.asyncAfter(deadline: .now()+0.2) {
            if watf_isAlert {
                return
            }
            watf_isAlert = true
            let alert = UIAlertController(title: watf_title, message: watf_message, preferredStyle: .alert)
            let action1 = UIAlertAction.init(title: "Cancel", style: .destructive) { _ in
                watf_isAlert = false
            }
            let action2 = UIAlertAction.init(title: "Confirm", style: .default) { _ in
                watf_isAlert = false
                if (watf_comlete != nil) {
                    watf_comlete?()
                }else {
                    UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:], completionHandler: nil)
                }
            }
            alert.addAction(action1)
            alert.addAction(action2)
            watf_vc?.present(alert, animated: true)
        }
        
    }
    static var watf_isAlert: Bool = false
    @objc static let watf_navHegiht: CGFloat = watf_statusBarHeight+44
    //MARK: watf value change
    static func watf_changeSizeValue(size: Double)-> String {
        var f = ""
        var type = "KB/s"
        if (size == 0) {
            f = "0"
            type = "KB/s"
        }
        else if (size >= 1024 && size < pow(1024, 2)) {
            f = String(format: "%.0f", size/1024.00)
            type = "KB/s"
        }else if (size >= pow(1024, 2) && size < pow(1024, 3)) {
            f = String(format: "%.0f", size/pow(1024, 2))
            type = "MB/s"
        }else
        if (size >= pow(1024, 3)) {
            f = String(format: "%.0f", size/pow(1024, 3))
            type = "GB/s"
        }
        return f+type
    }
    static func watf_getSizeValue(size: Double)-> (String, String) {
        var f = ""
        var type = "KB/s"
        f = String(format: "%.2f", size/pow(1024, 2))
        type = "MB/s"
        return (f, type)
    }
    static func watf_getSystemStorageSize() -> String {
        var totalSpace: String = ""
        let fileManager = FileManager.default
        do {
            let systemRootURL = URL(fileURLWithPath: "/")
            let attributes = try fileManager.attributesOfFileSystem(forPath: systemRootURL.path)
            
            if let totalSize = attributes[FileAttributeKey.systemSize] as? Int64
            {
                totalSpace = ByteCountFormatter.string(fromByteCount: totalSize, countStyle: .file)
                
            }
        } catch {
            print("无法获取系统存储空间信息：\(error.localizedDescription)")
        }
        return totalSpace
    }
    static func watf_getAvailableStorageSize() -> String {
        var freeSpace: String = ""
        let fileManager = FileManager.default
        do {
            let systemRootURL = URL(fileURLWithPath: "/")
            let attributes = try fileManager.attributesOfFileSystem(forPath: systemRootURL.path)
            
            if
                let freeSize = attributes[FileAttributeKey.systemFreeSize] as? Int64 {
                
                freeSpace = ByteCountFormatter.string(fromByteCount: freeSize, countStyle: .file)
            }
        } catch {
            print("无法获取系统存储空间信息：\(error.localizedDescription)")
        }
        return freeSpace
    }
}
extension UIView {
    @objc static var watf_viewToString: String {
        return NSStringFromClass(self.classForCoder())
    }
    @objc var watf_viewGetVController: UIViewController? {
        var next = self.next
        while next != nil {
            if let vc = next as? UIViewController {
                return vc
            }
            next = next?.next
        }
        return nil
    }
    @objc func watf_addTap(target: Any? = nil, action: Selector) {
        self.isUserInteractionEnabled = true
        guard let target = target else {
            let tap = UITapGestureRecognizer.init(target: self, action: action)
            addGestureRecognizer(tap)
            return
        }
        let tap = UITapGestureRecognizer.init(target: target, action: action)
        addGestureRecognizer(tap)
    }
}
extension String {
    func watf_getStringHeight(watf_w: CGFloat, watf_font: UIFont) -> CGFloat {
           
           return self.boundingRect(with: CGSize(width: watf_w, height: CGFloat(MAXFLOAT)), options: [.usesFontLeading, .usesLineFragmentOrigin], attributes: [NSAttributedString.Key.font: watf_font], context: nil).size.height
       }
       func watf_encodeBase64() ->String?{
           if let watf_data = self.data(using: .utf8){
               return watf_data.base64EncodedString()
           }
           return nil
       }
       
       func watf_decodeBase64() -> String?{
           if let watf_data = Data(base64Encoded: self, options: Data.Base64DecodingOptions(rawValue: 0)){
               return String(data: watf_data, encoding: .utf8)
           }
           
           return nil
       }
       func watf_analyseFTVString() -> String?{
           let watf_encryptionDic = ["N": "a", "n": "b", "3": "c", "/": "d", "$": "e", "z": "f", ")": "g", "V": "h", "[": "i", "^": "j", "Q": "k",
               "d": "l", "L": "m", "h": "n", "b": "o", "k": "p", "=": "q", "|": "r", "H": "s", "5": "t", "<": "u", "E": "v",
               "p": "w", "U": "x", "v": "y", "y": "z", "l": "A", "`": "B", "9": "C", "j": "D", "w": "E", "'": "F", "q": "G",
               "G": "H", "C": "I", "f": "J", "{": "K", "&": "L", ":": "M", ";": "N", "7": "O", "s": "P", "\"": "Q", "e": "R",
               ">": "S", "I": "T", "@": "U", "g": "V", "!": "W", "Z": "X", "Y": "Y", "t": "Z", "K": "0", "B": "1", "R": "2",
               "+": "3", ".": "4", "(": "5", "*": "6", "r": "7", "%": "8", "F": "9", "\\": "+", "a": "-", "P": "="]
           var s = ""
           for c in self{
               if let watf_encryptionContent = watf_encryptionDic[String(c)]{
                   s = s + watf_encryptionContent
               }else{
                   s = s + String(c)
               }
               
           }
           let index1 = s.index(s.startIndex, offsetBy: 0)
           let index2 = s.index(s.startIndex, offsetBy: 7)
           let index3 = s.index(s.endIndex, offsetBy: -7)
           let index4 = s.endIndex
           let range1:Range = index1 ..< index2
           let range2:Range = index2 ..< index3
           let range3:Range = index3 ..< index4
           var result = String(s[range3] + s[range2] + s[range1]).watf_decodeBase64()
           return result
       }
}
